<template>
  <div>
    <b-table
      ref="table"
      bordered
      :columns="columns"
      :out-loading="loading"
      :request="loadData"
      :del-func="delFunc"
      :disabled="disabled"
      :scroll="{ x: 1300 }"
      :export-config="{use:true,select:'物资消耗明细',all:'物资消耗明细'}"
      :is-show-count-bar="false"
    >
      <!--      <template slot="prefix" slot-scope="ref">-->
      <!--        <a-button type="primary" @click="openDialog()" :loading="loadingAdd">添加</a-button>-->
      <!--      </template>-->
      <template slot="suffix" slot-scope="ref">
        <a-button type="primary" @click="openDialog(downloadApi)" :loading="loadingAdd">标准模板下载</a-button>
        <ExcelImportButton v-if="!disabled" @handleSubmit="importFunc" />
      </template>
      <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
      <template
        v-for="col in ['inventoryAmount','purchaseAmount','callInAmount',
        'callOutAmount','loseAmount','liveWoodAmount',
                       'finishedProductAmount','remark']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="!disabled">
            <BaseInputNumber
              class="requiredFormItem"
              v-if="col !== 'remark'"
              v-model="record[col]"
              :precision="2"
              @blur="save(record)"
            />
            <BaseInput v-if="col === 'remark'" v-model="record[col]" @blur="save(record)" />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </b-table>
    <material-list-and-dir
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import Api from '@/api/material/inventory/sceneConsumeMaterialDetail'

export default {
  props: {
    disabled: {
      type: Boolean
    },
    id: {
      type: String
    }
  },
  data() {
    return {
      loading: false,
      loadingAdd: false,
      columns: [
        { title: '序号', width: 70, scopedSlots: { customRender: 'index' } },
        { title: '物资名称', width: 200, dataIndex: 'materialName' },
        { title: '物料编码', width: 130, dataIndex: 'materialCode' },
        { title: '单位', width: 80, dataIndex: 'materialUnit' },
        { title: '上月盘点数量', width: 150, dataIndex: 'inventoryAmount', scopedSlots: { customRender: 'inventoryAmount' } },
        { title: '本月采购数量', width: 150, dataIndex: 'purchaseAmount', scopedSlots: { customRender: 'purchaseAmount' } },
        { title: '本月调入数量', width: 150, dataIndex: 'callInAmount', scopedSlots: { customRender: 'callInAmount' } },
        { title: '本月调出数量', width: 150, dataIndex: 'callOutAmount', scopedSlots: { customRender: 'callOutAmount' } },
        { title: '本月丢失数量', width: 150, dataIndex: 'loseAmount', scopedSlots: { customRender: 'loseAmount' } },
        { title: '本月库存原材数量', width: 150, dataIndex: 'liveWoodAmount', scopedSlots: { customRender: 'liveWoodAmount' } },
        {
          title: '本月成品、半成品数量',
          width: 150,
          dataIndex: 'finishedProductAmount',
          scopedSlots: { customRender: 'finishedProductAmount' }
        },
        { title: '本月工程消耗数量', width: 150, dataIndex: 'consumptionAmount' },
        { title: '备注', width: 250, dataIndex: 'remark', scopedSlots: { customRender: 'remark' } }
      ],
      downloadApi: Api.downMaterialSceneConsumeExcel,
      delFunc: Api.deleteByDetails,
      loadData: params => Api.findListByDetails(Object.assign(params, { query: { baseId: this.id } }))
    }
  },
  methods: {
    async importFunc(e) {
      // this.$console(e)
      let newTable = []
      let checkRes = true
      e.map(row => {
        let temp = {}
        for (const rowKey in row) {
          let column = this.columns.find(columnRow => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            temp[dataIndex] = row[rowKey]
            if (checkRes && rowKey === '上月盘点数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '本月采购数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '本月调入数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '本月调出数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '本月丢失数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '本月库存原材数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '本月成品、半成品数量' && typeof row[rowKey] !== 'number') checkRes = false
          }
        }
        temp.baseId = this.id
        newTable.push(temp)
      })
      if (!checkRes) {
        return this.$noticeWarning('数据格式错误！')
      }
      this.loading = true
      let res = await Api.createByDetails(newTable)
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        if (res.message === '操作成功！') {
          this.$noticeSuccess('导入成功！')
          this.$refs.table.getData(null, true)
        } else {
          this.$notification.open({ message: '提示', duration: null, description: () => <pre>{res.message}</pre> })
        }
      }
    },
    async openDialog(downloadApi) {
      let allData = []
      if (this.$refs.table.totalSize !== 0) {
        this.loadingAdd = true
        let res = await Api.findListByDetails({
          pageSize: this.$refs.table.totalSize,
          pageNo: 1,
          query: { baseId: this.id }
        })
        this.loadingAdd = false
        if (res.code === this.SUCCESS_CODE) {
          allData = res.data
        }
      }
      if (downloadApi) {
        let fileName = '标准模板下载.xlsx'
        this.$refs.detailDialog.download(allData, downloadApi)
      } else {
        this.$refs.detailDialog.open(allData)
      }
    },
    async createList(selectRows) {
      let params = []
      selectRows.map(selectRow => {
        params.push({
          materialName: selectRow.materialName,
          materialCode: selectRow.materialCode,
          materialModel: selectRow.specificationModel,
          materialUnit: selectRow.unit,
          materialId: selectRow.id,
          baseId: this.id
        })
      })
      this.loading = true
      let res = await Api.createByDetails(params)
      this.loading = false
      if (res.code === 200) {
        this.$refs.table.refresh()
      }
    },
    save(target) {
      target.baseId = this.id
      try {
        if (
          target.inventoryAmount !== null && target.purchaseAmount !== null && target.callInAmount !== null &&
          target.callOutAmount !== null && target.loseAmount !== null && target.liveWoodAmount !== null &&
          target.finishedProductAmount
        ) {
          target.consumptionAmount =
            target.inventoryAmount +
            target.purchaseAmount +
            target.callInAmount -
            target.callOutAmount -
            target.loseAmount -
            target.liveWoodAmount -
            target.finishedProductAmount

          if (target.consumptionAmount < 0) {
            target.consumptionAmount = ''
            return this.$noticeError('本月工程消耗数量不能小于0，自动保存失败！')
          }
          target.consumptionAmount = target.consumptionAmount.toFixed(2)
        } else {
          target.consumptionAmount = null
        }
      } catch (e) {
      }
      Api.editByDetails(target).then(res => {
        if (res.code !== 200) this.$noticeWarning(res.message)
      })
    }

  }
}
</script>
